// Copyright (C) 2011 and onwards Noam Shazeer and Georges Harik

#ifndef __SERVER_H_
#define __SERVER_H_

#include <sys/socket.h>
#include <netinet/in.h>
#include "util.h"

bool IsURLSafe(char c);

string URLEncode(const string & s);
string URLDecode(const string & s);
inline char Hex(int i) {
  if (i < 10) return '0' + i;
  return 'A' + (i-10); }
inline int HexToInt(char c) {
  if (isdigit(c)) return c-'0';
  if (isupper(c)) return c - 'A' + 10;
  return c-'a' + 10;
}

struct WebRequest { 
  string path_;
  map<string, string> params_;
  string ToString() const;
};

struct WebBackend {
  virtual string Serve(WebRequest request) { return request.ToString(); }
};

struct WebServer {
  WebServer(int port, WebBackend *web_backend)
  :port_(port), web_backend_(web_backend) {}
  
  // PUBLIC
  void Launch();
  
  // Private
  void LoopInternal();
  bool IsCompleteRequest(int so_far);
  void ReadRequest();
  void ParseRequest();
  void Reply();

  int port_;
  WebBackend *web_backend_;
  

  int s_socket_;
  int c_socket_;
  struct sockaddr_in s_address_;
  struct sockaddr_in c_address_;
  string request_;
  WebRequest w_request_;
  string reply_;
  char * buffer_;
};

void * WebServerThread(void *ws);


#endif
